import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

import '../../EcyRouter.dart';
import '../../constant/EcyEventConsnt.dart';
import '../../ecycommon/EcyEventBus.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyLogger.dart';
import '../../model/EcyApiCommonPage.dart';
import '../../model/EcyApiCommonResponse.dart';
import 'model/messgae/ChatSession.dart';
import 'package:ecy_app_flutter/routes/my/EcySystemNoticePage.dart';

class EcyMyMessagePage extends StatefulWidget {
  const EcyMyMessagePage({required super.key});

  @override
  State<StatefulWidget> createState() => _EcyMyMessagePageState();
}

class _EcyMyMessagePageState extends State<EcyMyMessagePage> {
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int _total = 0;
  int _page = 1;
  final List<ChatSession> _chatSessionList = [];

  @override
  void initState() {
    super.initState();

    _refreshData();
  }

  void _onRefresh() async {
    _page = 1;
    await _refreshData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    if (_page < _total) {
      await _refreshData(page: ++_page);
    }
    _refreshController.loadComplete();
  }

  Future<void> _refreshData({int page = 1}) async {
    try {
      Map<String, dynamic> body = {
        "size": 15,
        "current": page,
      };
      var response = await EcyRequestbasemanager()
          .get("/app/api/app/consign/sessions", body);
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<ChatSession> commonPage = EcyApiCommonPage.fromJson(
              response["data"], (json) => ChatSession.fromJson(json));
          _total = commonPage.pages ?? 0;
          _page = commonPage.current ?? 0;
          if (page == 1) {
            _chatSessionList.clear();
          }
          setState(() {
            _chatSessionList.addAll(commonPage.records ?? []);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取我的消息失败$e");
    }
  }

  Future<void> _messagesRead(int sessionId) async {
    try {
      await EcyRequestbasemanager().put("/app/api/app/consign/messages/read", {
        "sessionId": sessionId,
      });
    } catch (e) {
      EcyLogger.log("标记消息为已读失败$e");
    } finally {
      //发送全局通知
      EcyEventBus().emit(EcyEventConst.kMessagesRead);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        scrolledUnderElevation: 0,
        backgroundColor: Colors.white,
        elevation: 0,
        leadingWidth: 50.w,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.pop(context, "");
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 24.w,
            ),
          ),
        ),
        titleSpacing: 0,
        centerTitle: true,
        title: Text("消息",
            style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w600,
                fontSize: 16.sp,
                color: const Color(0xFF262626))),
      ),
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: const ClassicHeader(
          idleText: "下拉刷新",
          refreshingText: "正在刷新",
          completeText: "刷新完成",
          failedText: "刷新失败",
          releaseText: "释放刷新",
        ),
        footer: const ClassicFooter(
          idleText: "上拉加载更多",
          loadingText: "正在加载",
          noDataText: "没有更多数据",
          failedText: "加载失败",
          canLoadingText: "释放加载更多",
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: _buildMessageList(),
      ),
    );
  }

  Widget _buildMessageList() {
    if (_chatSessionList.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/images/empty/ic_empty_search.png',
              width: 120.w,
              height: 120.w,
            ),
            SizedBox(height: 12.h),
            Text(
              '暂无消息',
              style: TextStyle(
                fontSize: 14.sp,
                color: const Color(0xFF999999),
              ),
            ),
          ],
        ),
      );
    }

    return ListView(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      children: [
        // 系统通知 
        _buildSystemNotification(),
        // 互动消息
        _buildInteractionMessage(),
        // 聊天消息列表
        ..._chatSessionList
            .map((session) => _buildMessageItem(session))
            .toList(),
      ],
    );
  }

  Widget _buildSystemNotification() {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      child: InkWell(
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        onTap: () {
          EcyRouter.push(context, EcyRouter.systemNoticePage, null);
        },
        child: Row(
          children: [
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: const Color(0xFF4080FF),
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Icon(
                Icons.notifications,
                color: Colors.white,
                size: 24.w,
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "系统通知",
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500,
                      color: const Color(0xFF262626),
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    "你的包裹正在派送中",
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: const Color(0xFF999999),
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
              decoration: BoxDecoration(
                color: const Color(0xFFFF4D4F),
                borderRadius: BorderRadius.circular(10.r),
              ),
              child: Text(
                "99",
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.white,
                ),
              ),
            ),
            SizedBox(width: 8.w),
            Text(
              "昨天",
              style: TextStyle(
                fontSize: 12.sp,
                color: const Color(0xFF999999),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInteractionMessage() {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      child: InkWell(
        onTap: () {
          // 处理互动消息点击
        },
        child: Row(
          children: [
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: const Color(0xFFFF4D4F),
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Icon(
                Icons.chat_bubble,
                color: Colors.white,
                size: 24.w,
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "互动消息",
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500,
                      color: const Color(0xFF262626),
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    "爱吃甜甜圈评论了你",
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: const Color(0xFF999999),
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
              decoration: BoxDecoration(
                color: const Color(0xFFFF4D4F),
                borderRadius: BorderRadius.circular(10.r),
              ),
              child: Text(
                "2",
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.white,
                ),
              ),
            ),
            SizedBox(width: 8.w),
            Text(
              "刚刚",
              style: TextStyle(
                fontSize: 12.sp,
                color: const Color(0xFF999999),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMessageItem(ChatSession chatSession) {
    return SlidableAutoCloseBehavior(
      child: Slidable(
        key: Key('${chatSession.sessionId}'),
        endActionPane: ActionPane(
          motion: const ScrollMotion(),
          extentRatio: 0.3,
          children: [
            CustomSlidableAction(
              backgroundColor: const Color(0xFFFF4D4F),
              onPressed: (context) async {
                await _showDeleteConfirmDialog(chatSession);
              },
              child: Text(
                '删除',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
        child: InkWell(
          onTap: () {
            if (chatSession.sessionId != null &&
                (chatSession.unreadCount ?? 0) > 0) {
              setState(() {
                chatSession.unreadCount = 0;
              });
              _messagesRead(chatSession.sessionId!);
            }
            EcyRouter.push(context, EcyRouter.chatScreen, {"chatSession": chatSession});
          },
          child: Padding(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5), child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(20.r),
                child: CachedNetworkImage(
                  width: 40.w,
                  height: 40.w,
                  imageUrl: chatSession.fromUserImageUrl ?? "",
                  imageBuilder: (context,
                      imageProvider) =>
                      Container(
                        decoration: BoxDecoration(
                            image: DecorationImage(
                                image:
                                imageProvider,
                                fit: BoxFit.cover)),
                      ),
                  placeholder: (context, url) => Container(
                    color: const Color(0xFFF5F5F5),
                    child: Icon(
                      Icons.person,
                      size: 24.w,
                      color: const Color(0xFF999999),
                    ),
                  ),
                  errorWidget: (context, url, error) => Container(
                    color: const Color(0xFFF5F5F5),
                    child: Icon(
                      Icons.person,
                      size: 24.w,
                      color: const Color(0xFF999999),
                    ),
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      chatSession.counterpartName ?? "未知用户",
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w500,
                        color: const Color(0xFF262626),
                      ),
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      chatSession.lastMessage??"",
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: const Color(0xFF999999),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
              if ((chatSession.unreadCount ?? 0) > 0)
                Container(
                  padding:
                  EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFF4D4F),
                    borderRadius: BorderRadius.circular(10.r),
                  ),
                  child: Text(
                    '${chatSession.unreadCount}',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.white,
                    ),
                  ),
                ),
              SizedBox(width: 8.w),
              Text(
                _formatTime(chatSession.updateTime ?? ""),
                style: TextStyle(
                  fontSize: 12.sp,
                  color: const Color(0xFF999999),
                ),
              ),
            ],
          ),),
        ),
      ),
    );
  }

  Future<void> _showDeleteConfirmDialog(ChatSession session) async {
    bool? confirm = await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("删除会话"),
          content: const Text("确认删除该会话吗？"),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: Text(
                "取消",
                style: TextStyle(
                  color: const Color(0xFF999999),
                  fontSize: 14.sp,
                ),
              ),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: Text(
                "删除",
                style: TextStyle(
                  color: const Color(0xFFFF4D4F),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        );
      },
    );

    if (confirm == true) {

      var response = await EcyRequestbasemanager()
          .delete("/app/api/app/consign/sessions/${session.sessionId}", {});
      if (response != null) {
        var commonResponse =
        EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          setState(() {
            _chatSessionList
                .removeWhere((item) => item.sessionId == session.sessionId);
          });
        }
      }
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('会话已删除'),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(4.r),
            ),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    }
  }

  String _formatTime(String time) {
    if (time.isEmpty) return "";
    try {
      final DateTime now = DateTime.now();
      final DateTime messageTime = DateTime.parse(time);
      final Duration difference = now.difference(messageTime);

      if (difference.inDays == 0) {
        return "今天";
      } else if (difference.inDays == 1) {
        return "昨天";
      } else if (difference.inDays < 7) {
        return "${difference.inDays}天前";
      } else {
        return "${messageTime.month}-${messageTime.day}";
      }
    } catch (e) {
      return "";
    }
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }
}
